//
//  PKReadWebViewController.m
//  PianKe
//
//  Created by lanou on 15/12/29.
//  Copyright (c) 2015年 KFC. All rights reserved.
//


// 注意:阅读的webviewController界面是在webview上的scrollview上加一个view用来展示作者信息
// 不同于:社区界面,社区界面是在最下层加一个mainScrollView,再在它上面添加webview,以及各种view展示信息



#import "PKReadWebViewController.h"
#import "PKReadBookModel.h"
#import "PKReadDetailViewController.h"
#import "PKReadCommentTableViewController.h"
#import "UMSocial.h"
@interface PKReadWebViewController ()<UIWebViewDelegate>

@property (strong, nonatomic) UIWebView *webView;
@property (strong, nonatomic) UIView *InfoView;
@property (assign, nonatomic) CGFloat height;
// 数据源model
@property (strong, nonatomic) PKReadBookModel *bookModel;
// 自定义导航栏
@property (strong, nonatomic) UIView *headView;
// 判断功能view有没有显示出来
@property (assign, nonatomic) BOOL isNotExistButtonView;

// 评论数
@property (strong, nonatomic) UILabel *commentLabel;
// 喜欢数
@property (strong, nonatomic) UILabel *fontLabel;



@end

@implementation PKReadWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
  
#pragma mark ---- 铺设界面:自定义导航栏,添加webview
    [self addViews];
#pragma mark ---- 解析文章数据,获取作者信息
    [self setUpData];
}


#pragma mark ----  解析文章的数据 , 并在加载完数据后,展示webview上的信息:
// 在加载完信息后再展示webview是防止:在没有解析出作者信息,就展示webview,但webview上有作者的信息的view,此时,没有能赋值的model,就会崩溃
- (void)setUpData
{
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"auth"] = @"";
    parDic[@"client"] = @"1";
    parDic[@"deviceid"] = @"63A94D37-33F9-40FF-9EBB-481182338873";
    parDic[@"version"] = @"3.0.2";
    parDic[@"contentid"] = _url;
    
    [PKRequestManager requestWithUrlString:@"http://api2.pianke.me/article/info" parDic:parDic Method:POST finish:^(NSData *data) {
        NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        NSDictionary *dataDic = dic[@"data"];
        _bookModel = [[PKReadBookModel alloc] init];
        [_bookModel setValuesForKeysWithDictionary:dataDic];        
        
        [self showWeb];
    } error:^(NSError *error) {
        NSLog(@"%@",error);
        
    }];
    
}

#pragma mark ---- 铺设界面的实现 : 自定义导航栏 + 创建webview
- (void)addViews
{
    // 创建自定义导航栏
    _headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 64*kHeightBase)];
    _headView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_headView];
    [self.view bringSubviewToFront:_headView];
    // 返回按钮
    UIButton *leftBack = [UIButton buttonWithType:(UIButtonTypeCustom)];
    leftBack.frame = CGRectMake(10*kWidthBase, 30*kHeightBase, 30*kWidthBase, 30*kHeightBase);
    [leftBack setBackgroundImage:[UIImage imageNamed:@"fanhui"] forState:(UIControlStateNormal)];
    [leftBack addTarget:self action:@selector(backAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [_headView addSubview:leftBack];
    // 分割线
    UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(leftBack.right + 10*kWidthBase, 20*kHeightBase, 1, 40*kHeightBase)];
    line.backgroundColor = [UIColor silverColor];
    [_headView addSubview:line];
    // 功能按钮:实现字体,日夜模式
    UIButton *changeButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    changeButton.frame = CGRectMake(line.right + 10*kWidthBase, leftBack.top + 2.5*kHeightBase, leftBack.height - 5*kHeightBase , leftBack.height - 5*kHeightBase);
    changeButton.layer.cornerRadius = (leftBack.height - 5*kHeightBase) / 2;
    changeButton.layer.masksToBounds = YES;
    [changeButton setBackgroundImage:[UIImage imageNamed:@"iconfont-a"] forState:(UIControlStateNormal)];
    [_headView addSubview:changeButton];
    // 添加方法
    [changeButton addTarget:self action:@selector(changeButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    // 评论按钮
    UIButton *commentButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    commentButton.frame = CGRectMake(changeButton.right + 30*kWidthBase, changeButton.top, changeButton.width, changeButton.height);
    [commentButton setBackgroundImage:[UIImage imageNamed:@"iconfont-pinglun(1)"] forState:(UIControlStateNormal)];
    [_headView addSubview:commentButton];
    
    // 评论数
    _commentLabel = [[UILabel alloc] initWithFrame:CGRectMake(commentButton.right, commentButton.top, 40*kWidthBase, commentButton.height)];
    _commentLabel.textAlignment = NSTextAlignmentCenter;
    _commentLabel.font = [UIFont systemFontOfSize:12];
    // 赋值,我在showweb方法里面赋值,防止崩溃
    [_headView addSubview:_commentLabel];
    
    
    
    // 喜欢按钮
    UIButton *likeButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    likeButton.frame = CGRectMake(_commentLabel.right + 30*kWidthBase, _commentLabel.top, commentButton.width, commentButton.height);
    [likeButton setBackgroundImage:[UIImage imageNamed:@"iconfont-xihuan(1)"] forState:(UIControlStateNormal)];
    [_headView addSubview:likeButton];
    
    // 喜欢数
    _fontLabel = [[UILabel alloc] initWithFrame:CGRectMake(likeButton.right, likeButton.top, _commentLabel.width, _commentLabel.height)];
    _fontLabel.textAlignment = NSTextAlignmentCenter;
    _fontLabel.font = [UIFont systemFontOfSize:12];
    [_headView addSubview:_fontLabel];
    
    // 分享功能按钮
    UIButton *shareButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    shareButton.frame = CGRectMake(kScreenWidth - 60*kWidthBase, _fontLabel.top, likeButton.width, likeButton.height);
    [shareButton setBackgroundImage:[UIImage imageNamed:@"iconfont-gengduo"] forState:(UIControlStateNormal)];
    [_headView addSubview:shareButton];
    
    // 给评论按钮,喜欢按钮,更多按钮添加方法
    [commentButton addTarget:self action:@selector(commentAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [likeButton addTarget:self action:@selector(likeAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [shareButton addTarget:self action:@selector(shareAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    // 分割线:
    UILabel *line2 = [[UILabel alloc] initWithFrame:CGRectMake(0, 64*kHeightBase, kScreenWidth, 1)];
    line2.backgroundColor = [UIColor silverColor];
    [self.view addSubview:line2];
    
    // 创建webview:
    _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 65*kHeightBase, kScreenWidth, kScreenHeight - 64)];
    _webView.delegate = self;
    _webView.backgroundColor = [UIColor whiteColor];
    NSLog(@"%@",_url);
    [self.view addSubview:_webView];
    
   
    
}

#pragma mark ---- 喜欢按钮的方法的实现
- (void)likeAction:(UIButton *)button
{
    
    
}
#pragma mark ---- 评论按钮的方法的实现
- (void)commentAction:(UIButton *)button
{
    
    PKReadCommentTableViewController *commentVC = [[PKReadCommentTableViewController alloc]init];
    [self.navigationController pushViewController:commentVC animated:YES];
    
}

#pragma mark  ----  实现分享功能
- (void)shareAction:(UIButton *)button
{
    
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"5689e5f467e58e978f00129a"
                                      shareText:@"你要分享的文字"
                                     shareImage:[UIImage imageNamed:@"icon.png"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToWechatSession,UMShareToQQ,UMShareToTencent,UMShareToRenren,UMShareToDouban,UMShareToEmail,UMShareToWechatTimeline,nil]
                                       delegate:nil];
}




#pragma mark ---- A功能按钮:出现功能按钮所在的视图:
- (void)changeButtonAction:(UIButton *)button
{
    _isNotExistButtonView = !_isNotExistButtonView;
    
    if (_isNotExistButtonView == YES) {
        
        // 先添加按钮view
        UIView *buttonView = [[UIView alloc] initWithFrame:CGRectMake(0, -100*kHeightBase, kScreenWidth, 100*kHeightBase)];
        [buttonView setBackgroundColor:[UIColor colorWithRed:0.3
                                                       green:0.3
                                                        blue:0.3
                                                       alpha:0.7]];
        buttonView.tag = 666;
        [self.view addSubview:buttonView];
        
        
        
        UIButton *smallButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
        smallButton.frame = CGRectMake(20*kWidthBase, 10*kHeightBase, (kScreenWidth - (20+10+20)*kWidthBase)/2, (buttonView.height - 30*kHeightBase)/2);
        smallButton.backgroundColor = [UIColor whiteColor];
        [smallButton setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
        [smallButton setTitle:@"A-" forState:(UIControlStateNormal)];
        [buttonView addSubview:smallButton];
        
        UIButton *bigButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
        bigButton.frame = CGRectMake(smallButton.right + 10*kWidthBase, smallButton.top, smallButton.width, smallButton.height);
        bigButton.backgroundColor = [UIColor whiteColor];
        [bigButton setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
        [bigButton setTitle:@"A+" forState:(UIControlStateNormal)];
        [buttonView addSubview:bigButton];
        
        UIButton *dayButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
        dayButton.frame = CGRectMake(smallButton.left, smallButton.bottom + 10*kHeightBase, smallButton.width, smallButton.height);
        dayButton.backgroundColor = [UIColor whiteColor];
        [dayButton setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
        [dayButton setTitle:@"日间" forState:(UIControlStateNormal)];
        [buttonView addSubview:dayButton];
        
        UIButton *nightButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
        nightButton.frame = CGRectMake(bigButton.left, dayButton.top, bigButton.width, dayButton.height);
        nightButton.backgroundColor = [UIColor blackColor];
        [nightButton setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
        [nightButton setTitle:@"夜间" forState:(UIControlStateNormal)];
        [buttonView addSubview:nightButton];
        
        smallButton.tag = 200;
        bigButton.tag = 201;
        dayButton.tag = 202;
        nightButton.tag = 203;
        
        // 给四个button添加方法
        [smallButton addTarget:self action:@selector(buttonAction:) forControlEvents:(UIControlEventTouchUpInside)];
        [bigButton addTarget:self action:@selector(buttonAction:) forControlEvents:(UIControlEventTouchUpInside)];
        [dayButton addTarget:self action:@selector(buttonAction:) forControlEvents:(UIControlEventTouchUpInside)];
        [nightButton addTarget:self action:@selector(buttonAction:) forControlEvents:(UIControlEventTouchUpInside)];
        
        
        // 把headview放到最上面
        [self.view bringSubviewToFront:_headView];
        
        
        [UIView animateWithDuration:0.5 animations:^{
            
            buttonView.frame = CGRectMake(0, 64, kScreenWidth, 100*kHeightBase);
            
        }];

        
        
    } else {
        
        
        [UIView animateWithDuration:1 animations:^{
            
            UIView *view = (UIView *)[self.view viewWithTag:666];
            view.frame = CGRectMake(0, -100*kHeightBase, kScreenWidth, 100*kHeightBase);
            
        } completion:^(BOOL finished) {
            
            // 移除掉:
            UIView *view = (UIView *)[self.view viewWithTag:666];
            [view removeFromSuperview];
            
        }];
        
        
       
        
        
    }
    
    
    
}

#pragma mark  ---- 实现buttonview上button的方法,字体大小,夜间模式 : 
// 因为我在登陆的时候,默认给了 字体大小 以及 日间模式 , 所以点击按钮是要先判断 :
- (void)buttonAction:(UIButton *)button
{
    NSInteger tag = button.tag;
    if (tag == 200) {
        // 字体变小:
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        NSInteger size = [userDefaults integerForKey:@"网页比例"];
        if(size > 30){
            size = size - 10;
            [userDefaults setInteger:size forKey:@"网页比例"];
            [userDefaults synchronize];
            
        }
        
    } else if (tag == 201){
        
        // 字体变大
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        NSInteger size = [userDefaults integerForKey:@"网页比例"];
        if(size < 180){
            size = size + 10;
            [userDefaults setInteger:size forKey:@"网页比例"];
            [userDefaults synchronize];
            
        }
    } else if (tag == 202) {
        // 点击日间模式按钮
        NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
        NSString *state = [userDefault objectForKey:@"日夜"];
        if ([state isEqualToString:@"night"]) {
            [userDefault setObject:@"day" forKey:@"日夜"];
            [userDefault synchronize];
        }
        
        
    } else {
        // 点击 夜间模式 按钮
        NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
        NSString *state = [userDefault objectForKey:@"日夜"];
        if ([state isEqualToString:@"day"]) {
            [userDefault setObject:@"night" forKey:@"日夜"];
            [userDefault synchronize];
        }
        
    }
    
    // 移除掉作者信息infoview,因为它本身并不属于webView,我们对webview的操作不会对infoview操作,所以,我们可以
    // 先把infoview从webview上去除掉,然后,再走一遍showweb方法,让webview再走一遍代理方法
    [_InfoView removeFromSuperview];
    
    // 刷新web页面
    [self showWeb];
    
    
    
}


#pragma mark ---  字符串加载形式来展示web内容
- (void)showWeb
{
    NSString *newUrl = [NSString stringWithFormat:@"http://pianke.me/webview/%@",_url];
    // 网址转data
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:newUrl]];
    // data转字符串
    NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    // 修改web上图片的大小
   // str = [NSString stringWithFormat:@"<head><style>img{width:%fpx !important;}</style></head>%@",kScreenWidth,str];
    // 加载字符串
    [_webView loadHTMLString:str baseURL:nil];
    
    _commentLabel.text = [NSString stringWithFormat:@"%@",_bookModel.comment];
    _fontLabel.text = [NSString stringWithFormat:@"%@",_bookModel.like];
    
    
}

#pragma mark --- 加一个web加载的判断:禁止:网页上其他链接的点击
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSLog(@"%@",request);
    // 获取网址
    NSURL *url = request.URL;
    // url 转 字符串
    NSString *str = url.absoluteString;
    if ([str isEqualToString:@"about:blank"]) {
        return  YES;
    }
    return NO;
}

#pragma mark --- UIWebView每次加载完毕后执行 的  代理方法
// 实现修改网页比例的大小 , 以及 添加作者信息的视图
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSInteger size = [userDefaults integerForKey:@"网页比例"];
    NSMutableString *scale = [NSMutableString stringWithFormat:@"%ld",size];
    [scale appendFormat:@"%%"];
    // 修改网页比例
    [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '%@'",scale]];
    // 获取webView的高度
    // 使用webView去执行一段JS脚本的代码,
    _height = [[_webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"] floatValue];
    
    // 先修改ScrollView的可活动区域:在
    _webView.scrollView.contentSize = CGSizeMake(0, _height+170*kHeightBase);
    // 再添加infoView
    _InfoView = [[UIView alloc] initWithFrame:CGRectMake(0, _height, kScreenWidth, 170*kHeightBase)];
    // 把InfoView添加到scrollView上
    [_webView.scrollView addSubview:_InfoView];
   
    // 修改背景颜色
    NSString *state = [userDefaults objectForKey:@"日夜"];
    if ([state isEqualToString:@"day"]) {
        
        //字体颜色
        [_webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextFillColor= 'black'"];
        //页面背景色
        [_webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.backgroundColor='white'"];
        _InfoView.backgroundColor = [UIColor whiteColor];
        _webView.scrollView.backgroundColor = [UIColor whiteColor];
        _headView.backgroundColor = [UIColor whiteColor];
        
    } else {
        
        //字体颜色
        [_webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextFillColor= 'white'"];
        //页面背景色
        [_webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.backgroundColor='black'"];
        
        _InfoView.backgroundColor = [UIColor blackColor];
        _webView.scrollView.backgroundColor = [UIColor blackColor];
        _headView.backgroundColor = [UIColor blackColor];
    }
    
    // 展示作者信息 : 添加控件到InfoView上
    UILabel *totalLabel = [[UILabel alloc] initWithFrame:CGRectMake(20*kWidthBase, 0, 50*kWidthBase, 40*kHeightBase)];
    totalLabel.text = @"作者信息";
    totalLabel.font = [UIFont systemFontOfSize:12];
    [_InfoView addSubview:totalLabel];
    
    UILabel *line1 = [[UILabel alloc] initWithFrame:CGRectMake(totalLabel.right + 5*kWidthBase, totalLabel.height / 2, kScreenWidth - (50 + 20 + 10)*kWidthBase, 1*kHeightBase)];
    line1.backgroundColor = [UIColor grayColor];
    [_InfoView addSubview:line1];

    UIImageView *headImageV = [[UIImageView alloc] initWithFrame:CGRectMake(totalLabel.left, totalLabel.bottom, 30*kWidthBase, 30*kHeightBase)];
    headImageV.backgroundColor = [UIColor yellowColor];
    headImageV.layer.cornerRadius = 15;
    headImageV.layer.masksToBounds = YES;
    [headImageV sd_setImageWithURL:[NSURL URLWithString:_bookModel.icon] placeholderImage:nil];
    [_InfoView addSubview:headImageV];
   
    UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(headImageV.right + 10*kWidthBase, headImageV.top, 200*kWidthBase, headImageV.height)];
    nameLabel.font = [UIFont systemFontOfSize:13];
    nameLabel.textColor = [UIColor grayColor];
    nameLabel.text = _bookModel.uname;
    [_InfoView addSubview:nameLabel];
    
    UILabel *contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(headImageV.right, headImageV.bottom + 5*kHeightBase, kScreenWidth - 2 * headImageV.right, 50*kHeightBase)];
    contentLabel.numberOfLines = 0;
    // contentLabel.backgroundColor = [UIColor redColor];
    contentLabel.textColor = [UIColor grayColor];
    contentLabel.font = [UIFont systemFontOfSize:13];
    contentLabel.text = _bookModel.desc;
    [_InfoView addSubview:contentLabel];
    
    UIButton *button = [UIButton buttonWithType:(UIButtonTypeCustom)];
    button.frame = CGRectMake(kScreenWidth - 60*kWidthBase, headImageV.top, 40*kWidthBase, 20*kHeightBase);
    [button setTitle:@"关注" forState:(UIControlStateNormal)];
    button.layer.cornerRadius = 8;
    button.layer.masksToBounds = YES;
    button.backgroundColor = [UIColor greenColor];
    button.titleLabel.font = [UIFont systemFontOfSize:12];
    [_InfoView addSubview:button];

    UILabel *line2 = [[UILabel alloc] initWithFrame:CGRectMake(0, contentLabel.bottom + 5*kHeightBase, kScreenWidth, 1*kHeightBase)];
    line2.backgroundColor = [UIColor grayColor];
    [_InfoView addSubview:line2];
    
    UIButton *moreButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    moreButton.frame = CGRectMake(0, line2.bottom, kScreenWidth, _InfoView.height - line2.bottom);
   // moreButton.backgroundColor = [UIColor greenColor];
    [moreButton setTitle:[NSString stringWithFormat:@"查看“%@”的全部文章   -->",_bookModel.typeName] forState:(UIControlStateNormal)];
    moreButton.titleLabel.font = [UIFont systemFontOfSize:12];
    [moreButton setTitleColor:[UIColor greenColor] forState:(UIControlStateNormal)];
    [moreButton setTitleEdgeInsets:UIEdgeInsetsMake(moreButton.height / 3, 180*kWidthBase, moreButton.height / 3, 20*kHeightBase)];
    [_InfoView addSubview:moreButton];
    [moreButton addTarget:self action:@selector(moreArticle:) forControlEvents:(UIControlEventTouchUpInside)];
   
}


#pragma mark ---- 作者信息上的跟多文章按钮
- (void)moreArticle:(UIButton *)button
{
    PKReadDetailViewController *readDVC = [[PKReadDetailViewController alloc] init];
    readDVC.myTypeId = _bookModel.typeId;
    [self.navigationController pushViewController:readDVC animated:YES];

}

#pragma mark ---- 返回前一页按钮
- (void)backAction:(UIButton *)button
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
